#include "StdAfx.h"

#define _USE_MATH_DEFINES
#include <math.h>

#include "ColorUtils/Color.h"
#include "ColorUtils/Image.h"

#include "FirstIntersectionResult.h"
#include "SecondIntersectionResult.h"
#include "Intersectable.h"
#include "FlatSphere.h"

#include "TexturedSphere.h"

TexturedSphere::TexturedSphere(Point center, double radius, Image_ptr texturedImage) : FlatSphere(center, radius, Point(0, 0, 0)), _image(texturedImage)
{
}

void TexturedSphere::ColorAtIntersection(SecondIntersectionResult& result, const Point& point, const Ray&)
{
 	Point tempPoint(point - _center);

	double temp;
	double x = acos(tempPoint.Z / _radius);
	double y = 0;
	double temp2 = tempPoint.X / (_radius * sin(x));
	if ((temp = sin(x)) != 0)
		if (temp2 > 1)
			y = acos((double)1) / (2 * M_PI);
		else if(temp2 < -1)
			y = y = acos((double)-1) / (2 * M_PI);
		else
			y = acos(temp2) / (2 * M_PI);

	x /= M_PI;
	
	if (tempPoint.Y < 0)
  		y = -y;

   	y += 0.5;

	result.ColorAtPoint = _image->GetColor(x * _image->Width(), y * _image->Height());
}

TexturedSphere::~TexturedSphere(void)
{
}
